//
//  BLTabBarButton.m
//  新浪微博
//
//  Created by hbl on 16/2/14.
//  Copyright © 2016年 hbl. All rights reserved.
//

#import "BLTabBarButton.h"
#import "BLBadgeButton.h"

@interface BLTabBarButton()
@property (nonatomic, weak)BLBadgeButton *badgeButton;
@end
@implementation BLTabBarButton
- (void)setItem:(UITabBarItem *)item
{
    _item = item;
    [item addObserver:self forKeyPath:@"title" options:0 context:nil];
    [item addObserver:self forKeyPath:@"image" options:0 context:nil];
    [item addObserver:self forKeyPath:@"badgeValue" options:0 context:nil];
    [item addObserver:self forKeyPath:@"selectedImage" options:0 context:nil];
    [self observeValueForKeyPath:nil ofObject:nil change:nil context:nil];
   
    
}

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context
{
    [self setTitle:self.item.title forState:UIControlStateNormal];
    [self setTitle:self.item.title forState:UIControlStateHighlighted];
    [self setImage:self.item.image forState:UIControlStateNormal];
    [self setImage:self.item.selectedImage forState:UIControlStateSelected];
    self.badgeButton.badgeValue = self.item.badgeValue;
}
- (instancetype)initWithFrame:(CGRect)frame
{
    if (self = [super initWithFrame:frame]) {
        self.imageView.contentMode = UIViewContentModeCenter;
        self.titleLabel.textAlignment = NSTextAlignmentCenter;
        self.titleLabel.font = [UIFont systemFontOfSize:12];
        [self setTitleColor:[UIColor grayColor] forState: UIControlStateNormal];
        BLBadgeButton * badgeBtn = [[BLBadgeButton alloc]init];
//        badgeBtn.autoresizingMask = UIViewAutoresizingFlexibleRightMargin|UIViewAutoresizingFlexibleBottomMargin;
                      [self addSubview:badgeBtn];
        self.badgeButton = badgeBtn;
    }
    return self;
}

-(void)layoutSubviews
{
    [super layoutSubviews];
    self.badgeButton.center = CGPointMake(self.frame.size.width * 0.5, 0);
    self.badgeButton.layer.anchorPoint = CGPointMake(-0.1, 0);

    
}

- (void)setHighlighted:(BOOL)highlighted
{
    
}

- (CGRect)imageRectForContentRect:(CGRect)contentRect
{
    return CGRectMake(0, 0, contentRect.size.width, contentRect.size.height * 0.6);
}

- (CGRect)titleRectForContentRect:(CGRect)contentRect
{
    return CGRectMake(0, contentRect.size.height * 0.6, contentRect.size.width, contentRect.size.height * 0.4);
}

- (void)dealloc
{
    [self.item removeObserver:self forKeyPath:@"title"];
    [self.item removeObserver:self forKeyPath:@"image"];
    [self.item removeObserver:self forKeyPath:@"badgeValue"];
    [self.item removeObserver:self forKeyPath:@"selectedImage"];
}
@end
